package com.tarena.lbs.user.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.api.BusinessApi;
import com.tarena.lbs.business.api.pojo.BusinessDto;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;

import com.tarena.lbs.common.utils.PageConverter;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.param.AdminParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.query.AdminQuery;
import com.tarena.lbs.user.pojo.vo.AdminVO;
import com.tarena.lbs.user.service.AdminService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.tarena.lbs.user.enums.UserResultEnum.*;

@Service
public class AdminServiceImpl implements AdminService {
    private static final Logger log = LoggerFactory.getLogger(AdminServiceImpl.class);
    @Autowired
    private AdminRepository adminRepository;
    @DubboReference
    private BusinessApi businessApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AdminVO detail() throws BusinessException {
        UserPrinciple  userPrinciple = AuthenticationContextUtils.getUserPrinciple();
        Integer id=userPrinciple.getId();
        String redisKey = "admin:" + id;
        AdminVO adminVO = (AdminVO) redisTemplate.opsForValue().get(redisKey);
        if (adminVO==null){
            log.debug("用户详情缓存不存在,从数据库查询");
            AdminPO adminPO = adminRepository.selectById(id);
            adminVO = new AdminVO();
            if (adminPO!=null){
                BeanUtils.copyProperties(adminPO,adminVO);
                redisTemplate.opsForValue().set(redisKey, adminVO, 1, TimeUnit.HOURS);
            }
        }
        return adminVO;
    }

    @Override
    public PageResult<AdminVO> pageList(AdminQuery query) {
        log.debug("用户列表参数:{}",query);
        PageInfo<AdminPO> pageInfo=adminRepository.pageList(query);
        List<AdminPO> adminPOList = pageInfo.getList();
        List<AdminVO> adminVOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(adminPOList)){
           adminVOList=adminPOList.stream().map(adminPO -> {
               AdminVO adminVO = new AdminVO();
               BeanUtils.copyProperties(adminPO,adminVO);
               return adminVO;
           }).collect(Collectors.toList());
        }
        return PageConverter.convert(pageInfo, adminVOList);
    }

    @Override
    public void save(AdminParam param) throws BusinessException {
        log.debug("用户保存参数:{}",param);
        UserPrinciple  userPrinciple = AuthenticationContextUtils.getUserPrinciple();
        Roles loginRole = userPrinciple.getRole();
        Asserts.isTrue(loginRole!=Roles.ADMIN,new BusinessException(PURVIEW_NOT_EXISTS));
        AdminPO adminPO = new AdminPO();
        Long countByAccountPhone= adminRepository.selectByAccountPhone(param.getAccountPhone());
        Asserts.isTrue(countByAccountPhone>0, new BusinessException(PHONE_EXISTS));
        if (param.getAccountType()==1){
            BusinessDto businessVO = businessApi.getBusinessById(param.getBusinessId());
            Asserts.isTrue(businessVO==null,new BusinessException(BUSINESS_NOT_EXISTS));
        }
        BeanUtils.copyProperties(param,adminPO);
        adminPO.setCreateTime(new Date());
        adminPO.setBusinessId(param.getAccountType()==0?0:param.getBusinessId());
        adminRepository.save(adminPO);
    }

    @Override
    public void delete(Integer id) throws BusinessException {
        log.debug("用户删除参数:{}",id);
        UserPrinciple  userPrinciple = AuthenticationContextUtils.getUserPrinciple();
        Asserts.isTrue(userPrinciple.getRole()!=Roles.ADMIN,new BusinessException(PURVIEW_NOT_EXISTS));
        adminRepository.delete(id);
    }

    @Override
    public void resetPassword(Integer id) throws BusinessException {
        log.debug("用户密码重置参数:{}",id);
        UserPrinciple  userPrinciple = AuthenticationContextUtils.getUserPrinciple();
        Asserts.isTrue(userPrinciple.getRole()!=Roles.ADMIN,new BusinessException(PURVIEW_NOT_EXISTS));
        AdminPO adminPO = new AdminPO();
        adminPO.setAccountPassword("123456");
        adminPO.setId(id);
        adminRepository.resetPassword(adminPO);
    }


}
